package com.aizhixin.lab.company.service;

import com.aizhixin.lab.company.entity.Professional;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.company.domain.OrganDomain;
import com.aizhixin.lab.company.domain.SystemSetDomain;
import com.aizhixin.lab.company.entity.College;
import com.aizhixin.lab.company.entity.SystemSet;
import com.aizhixin.lab.company.entity.User;
import com.aizhixin.lab.company.repository.CollegeRepository;
import com.aizhixin.lab.company.repository.SystemSetRepository;

@Slf4j
@Service
@Transactional
public class CollegeService {
	@Autowired
	private CollegeRepository collegeRepository;
	@Autowired
	private ProfessionalService professionalService;

	public Map<String, Object> save(OrganDomain domain) {
		Map<String, Object> result = new HashMap<>();
		College college = null;
		if (null != domain.getId() && domain.getId() > 0) {
			college = collegeRepository.findOne(domain.getId());
			college.setName(domain.getName());
			college.setDescription(domain.getDescription());
		}else{
			college = new College();
			BeanUtils.copyProperties(domain, college);
		}
		collegeRepository.save(college);
		result.put(ApiReturnConstants.SUCCESS, true);

		return result;
	}
	
	public Map<String, Object> getAll() {
		Map<String, Object> result = new HashMap<>();
		List<College> collegeList = collegeRepository.findAllByDeleteFlagOrderById(DataValidity.VALID.getState());
		if (!collegeList.isEmpty()) {
			result.put(ApiReturnConstants.DATA, collegeList);
		}
		
		result.put(ApiReturnConstants.SUCCESS, true);

		return result;
	}
	
	
	public Map<String, Object> delete(OrganDomain domain) {
		Map<String, Object> result = new HashMap<>();
		College college = collegeRepository.findOne(domain.getId());

		if (null != college ) {
			List<Professional> allProfessional = professionalService.getAllProfessional(college.getId());
			List<Professional> newProfessional=new ArrayList<>();
			for (Professional p:allProfessional){
				p.setDeleteFlag(DataValidity.INVALID.getState());
				newProfessional.add(p);
			}
			professionalService.save(newProfessional);
			college.setDeleteFlag(DataValidity.INVALID.getState());
			collegeRepository.save(college);
			result.put(ApiReturnConstants.SUCCESS, true);
		}else{
			result.put(ApiReturnConstants.SUCCESS, false);
			result.put(ApiReturnConstants.ERROR, "学院信息不存在");
		}

		return result;
	}
}
